package cn.iocoder.yudao.module.system.tcpserver.protocol2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.ResourceLeakDetector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;

@Service
@Slf4j
public class NewNettyServer {
    /**
     * 通过springboot读取静态资源,实现netty配置文件的读写
     */
    @Value("${netty.new-bind-port}")
    private Integer port;

    @Value("${netty.boss_group_thread_count}")
    private Integer bossGroupThreadCount;

    @Value("${netty.worker_group_thread_count}")
    private Integer workerGroupThreadCount;

    @Value("${netty.leak_detector_level}")
    private String leakDetectorLevel;

    private ChannelFuture channelFuture;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    @Autowired
    private NewServerChannelInitializer newServerChannelInitializer;


    public void start() throws Exception {
        log.info("NNNN Setting resource leak detector level to {}", leakDetectorLevel);
        ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.valueOf(leakDetectorLevel.toUpperCase()));

        log.info("NNNN STARTING NETTY SERVER");
        //创建boss线程组 用于服务端接受客户端的连接
        bossGroup = new NioEventLoopGroup(bossGroupThreadCount);
        // 创建 worker 线程组 用于进行 SocketChannel 的数据读写
        workerGroup = new NioEventLoopGroup(workerGroupThreadCount);
        // 创建 ServerBootstrap 对象
        ServerBootstrap b = new ServerBootstrap();
        //设置使用的EventLoopGroup
        b.group(bossGroup, workerGroup)
                //设置要被实例化的为 NioServerSocketChannel 类
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 32)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.TCP_NODELAY, true)
                // 设置 NioServerSocketChannel 的处理器
                .handler(new LoggingHandler(LogLevel.WARN))
                // 设置连入服务端的 Client 的 SocketChannel 的处理器
                .childHandler(newServerChannelInitializer);
        // 绑定端口，并同步等待成功，即启动服务端
        channelFuture = b.bind(port).sync();

        log.info("NNNN NETTY SERVER STARTED!");

    }

    @PreDestroy
    public void shutdown() throws InterruptedException {
        log.info("NNNN Stopping Server");
        try {
            // 监听服务端关闭，并阻塞等待
            ChannelFuture channelFuture = this.channelFuture.channel()
                    .close().addListener(ChannelFutureListener.CLOSE);
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    log.info("NNNN Netty closed:{}", channelFuture.channel());
                }
            });
//            channelFuture.channel().closeFuture().sync();
            log.info("NNNN ~~~~~");
        } catch (Exception e) {
            log.error("NNNN shutdown error", e);
        } finally {
            // 优雅关闭两个 EventLoopGroup 对象
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
        log.info("NNNN server stopped!");

    }

}
